﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Sherwood.Mvc;
using Sherwood.SignOn.Server.Models.Services;
using Sherwood.SignOn.Server.Content;

namespace Sherwood.SignOn.Server.Models.ViewModels
{
    public class SendVerificationViewModel : ViewModelBase
    {
        public string RequestedUrl { get; set; }
        public Guid UserAccountId { get; set; }
        public string MessageToUser { get; set; }

        /// <summary>
        /// Resend verification email to the specified account (resets verification code etc).
        /// </summary>
        /// <param name="state"></param>
        /// <param name="userAccountId"></param>
        /// <returns></returns>
        public bool ResendVerificationEmail(ModelStateDictionary state)
        {
            bool emailSent = false;
            IUserAccount useraccount = Data.UserAccounts.GetUserAccount(UserAccountId);
            if (useraccount != null)
            {
                if (useraccount.VerificationStatus == VerificationStatus.Unverified)
                {
                    string code = "";
                    if (string.IsNullOrEmpty(useraccount.VerificationCode))
                    {
                        code = useraccount.CreateVerificationCode();
                    }
                    else
                    {
                        code = useraccount.VerificationCode;
                    }
                    useraccount.SetVerificationParameters(VerificationStatus.Unverified, RequestedUrl, code);
                    //Send email
                    string subject = Translations.Register_EMail_Subject.Parameterize(useraccount, this, Config.Settings);
                    string body = Translations.Register_Email_Template.Parameterize(useraccount, this, Config.Settings);
                    string emailError = "";
                    try
                    {
                        emailSent = EmailHelper.SendEmailToUser(subject, body, useraccount, useraccount.Email);
                        MessageToUser = Translations.SendVerification_Message.Parameterize(useraccount, this, Config.Settings);
                    }
                    catch (Exception ex)
                    {
                        emailSent = false;
                        emailError = ex.Message;
                    }
                }
            }
            if (!emailSent)
                MessageToUser = Translations.Register_Failed_To_Send_Email;
            return emailSent;
        }

    }
}
